const { code } = require("../utils/stateModel");
const Role = require("../db/models/roleSchema");
const Counter = require("../db/models/counterSchema");
const pagerFun = require("../utils/pager");
const { successModel, errorModel } = require("../utils/stateModel");
//查询角色
const rolelist = async (ctx, { roleName, pageNum, pageSize }) => {
  let params = {};
  let pager = {};
  if (roleName) params.roleName = roleName;
  const query = Role.find(
    params,
    "roleName permId remark permSign checkedKeys updateTime"
  );
  const rolelist = await query
    .skip(pagerFun(pageNum, pageSize).skipIndex)
    .limit(pagerFun(pageNum, pageSize).pager.pageSize);
  const total = await Role.countDocuments(params);
  pager.total = total;
  pager.pageNum = parseInt(pageNum);
  if (rolelist) {
    ctx.body = new successModel({ rolelist, pager });
    return;
  }
  return (ctx.body = new errorModel("查寻失败"));
};

const updateaddlist = async (ctx, { _id, action, ...updataPrams }) => {
  if (action) {
    try {
      const userList = await Role.findOneAndUpdate({ _id }, updataPrams);
      if (userList) {
        ctx.body = new successModel("修改成功");
        return;
      }
      return (ctx.body = new errorModel("修改失败"));
    } catch (error) {
      ctx.body = new errorModel(error.message);
      return;
    }
  }

  //新增角色
  if (!updataPrams.roleName) {
    ctx.body = new errorModel("参数错误", code.PARAM_ERROR);
    return;
  }
  const res = await Role.findOne({ $or: [{ roleName: updataPrams.roleName }] });

  if (res) {
    ctx.body = new errorModel(`新增用户名已存在:角色名:${res.roleName}`);
    return;
  }
  try {
    //这一步运行一次就可以注释掉，自增需要有个初始值
    const res = await Counter.findOne({ id: "roleid" });
    if (!res) {
      await Counter.create({
        id: "roleid",
        sequence_value: 0,
      });
    }
    //处理自增roleid
    const count = await Counter.findOneAndUpdate(
      { id: "roleid" },
      { $inc: { sequence_value: 1 } },
      { new: true }
    );
    const Roles = await new Role({
      roleId: count.sequence_value,
      ...updataPrams,
    });
    await Roles.save();
    ctx.body = new successModel("新增成功");
  } catch (error) {
    ctx.body = new errorModel(`新增失败${error}`, code.DB_ERROR);
  }
};

//删除角色（一般删除用户并非真正删除，而是改变状态，这里使用了真正的删除）
const dellist = async (ctx, { _id }) => {
  if (!_id) {
    ctx.body = new errorModel("参数错误", code.PARAM_ERROR);
    return;
  }
  //_id接收数组
  try {
    const res = await Role.deleteMany({ _id: { $in: _id } });
    ctx.body = new successModel(`删除成功${res.deletedCount}条`);
  } catch (error) {
    ctx.body = new errorModel("删除失败", code.DB_ERROR);
  }
};

module.exports = {
  rolelist,
  updateaddlist,
  dellist,
};
